package com.demo.eshop.pdetail.service.assyn.impl;

import com.demo.eshop.pdetail.request.Request;
import com.demo.eshop.pdetail.request.RequestQueue;
import com.demo.eshop.pdetail.service.assyn.RequestAsyncProcessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author: e20160504
 * @date: 2018/10/29
 * @desc
 */

@Service
public class RequestAsyncProcessServiceImpl implements RequestAsyncProcessService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void process(Request request) {
        try {
            // 做请求的路由，根据每个请求的商品ID，路由到对应队列中去
            ArrayBlockingQueue<Request> queue = getRoutingQueue(request.getProductId());
            // 将请求放入对应的队列,完成路由操作
            queue.put(request);

            logger.info("=====请求放入内存队列 队列size = {}",queue.size());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @params:
     * @return:
     * @desc: 根据商品ID 获取内存队列
     */
    private ArrayBlockingQueue<Request> getRoutingQueue(Integer productId) {
        RequestQueue requestQueue = RequestQueue.getInstance();
        String key = String.valueOf(productId);
        int h;
        int hash = (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        int index = (requestQueue.queueSize() - 1) & hash;

        logger.info("====路由开始将请求放入内存队列, 商品id = {}, 队列索引= {}",productId,index);

        return requestQueue.getQueue(index);
    }
}
